package com.example.service;

import com.example.config.MqttConfig;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MqttService {

    @Autowired
    private MqttClient mqttClient;

    @Autowired
    private MqttConfig mqttConfig;

    @PostConstruct
    public void init() {
        subscribeToTopics();
    }

    /**
     * 订阅主题
     */
    private void subscribeToTopics() {
        try {
            List<String> topics = mqttConfig.getTopics();
            for (String topic : topics) {
                mqttClient.subscribe(topic, (topic1, message) -> {
                    String payload = new String(message.getPayload());
                    log.info("收到消息 - 主题: {}, 内容: {}", topic1, payload);
                });
                log.info("已订阅主题: {}", topic);
            }
        } catch (MqttException e) {
            log.error("订阅主题失败: {}", e.getMessage());
        }
    }

    /**
     * 发布消息
     */
    public void publishMessage(String topic, String message) {
        try {
            MqttMessage mqttMessage = new MqttMessage(message.getBytes());
            mqttClient.publish(topic, mqttMessage);
            log.info("消息已发布到主题: {}, 内容: {}", topic, message);
        } catch (MqttException e) {
            log.error("发布消息失败: {}", e.getMessage());
        }
    }


    /**
     * 断开连接
     */
    public void disconnect() {
        try {
            if (mqttClient.isConnected()) {
                mqttClient.disconnect();
                log.info("MQTT连接已断开");
            }
        } catch (MqttException e) {
            log.error("断开连接失败: {}", e.getMessage());
        }
    }
}
